package com.qilu.careprogram.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许来自特定端口的请求
        //config.setAllowedOriginPatterns(Arrays.asList(
        //        "https://www.cxsh.asia:8082",
        //        "https://www.cxsh.asia:443",
        //        "https://cxsh.asia:8082",
        //        "https://cxsh.asia:443",
        //        "https://47.104.20.165:443",
        //        "https://47.104.20.165:8082"
        //));
        config.addAllowedOriginPattern("*");

        // 允许所有 HTTP 方法
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许携带凭证（如 cookie）
        config.setAllowCredentials(true);
        // 设置预检请求的有效期（秒）
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口都有效
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
